import { defineStore } from 'pinia'
import { weatherApi } from '../api'

export const useWeatherStore = defineStore('weather', {
  // 状态
  state: () => ({
    currentWeather: null,
    popularCities: [],
    searchHistory: [],
    searchResults: [], // 城市搜索结果
    loading: false,
    error: null
  }),
  
  // getters
  getters: {
    // 获取当前天气条件
    weatherCondition: (state) => {
      return state.currentWeather?.weather?.weatherCondition || '未知'
    },
    
    // 获取当前温度
    temperature: (state) => {
      return state.currentWeather?.weather?.temperature || null
    },
    
    // 获取预报数据
    forecasts: (state) => {
      return state.currentWeather?.weather?.forecasts || []
    }
  },
  
  // actions
  actions: {
    // 获取特定城市天气
    async getCityWeather(city, province) {
      this.loading = true
      this.error = null
      try {
        const response = await weatherApi.getCityWeather(city, province)
        this.currentWeather = response.data
        
        // 更新搜索历史
        this.updateSearchHistory(city, province)
        
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '获取天气信息失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 城市搜索
    async searchCity(keyword, options = {}) {
      this.loading = true
      this.error = null
      try {
        const response = await weatherApi.searchCity(keyword, options)
        this.searchResults = response.location || []
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '城市搜索失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取热门城市天气
    async getPopularCityWeather(params = {}) {
      this.loading = true
      this.error = null
      try {
        const response = await weatherApi.getPopularCityWeather(params)
        
        // 处理和风天气API返回的数据
        if (response.topCityList && response.topCityList.length > 0) {
          // 提取城市基本信息
          const cities = response.topCityList.map(city => ({
            id: city.id,
            city: city.name,         // 城市名称对应name字段
            province: city.adm1,     // 省份对应adm1字段
            temperature: city.temperature || 0,  // 使用API返回的温度，如果有的话
            icon: city.icon || '',   // 使用API返回的图标代码，如果有的话
            text: city.text || '',   // 使用API返回的天气文本，如果有的话
            weatherCondition: city.weatherCondition || '', // 使用API返回的天气状况，如果有的话
            lat: city.lat,
            lon: city.lon
          }));
          
          // 如果热门城市数据中没有天气信息，则需要单独获取每个城市的天气
          const citiesWithWeather = await Promise.all(
            cities.map(async (city) => {
              // 如果已经有温度和天气状况，则不需要再次请求
              if (city.temperature && city.weatherCondition) {
                return city;
              }
              
              try {
                // 获取城市天气数据
                const weatherResponse = await weatherApi.getCityWeather(city.city, city.province);
                const weather = weatherResponse.data.weather;
                
                // 更新城市天气信息
                return {
                  ...city,
                  temperature: weather.temperature || 0,
                  icon: weather.icon || '',
                  text: weather.text || weather.weatherCondition || '',
                  weatherCondition: weather.weatherCondition || ''
                };
              } catch (error) {
                console.error(`获取城市 ${city.city} 天气失败:`, error);
                return city;
              }
            })
          );
          
          this.popularCities = citiesWithWeather;
        } else {
          this.popularCities = [];
        }
        
        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '获取热门城市天气失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取多个城市天气
    async getMultiCityWeather(cities) {
      this.loading = true
      this.error = null
      try {
        const response = await weatherApi.getMultiCityWeather(cities)
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '获取多个城市天气失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新搜索历史
    updateSearchHistory(city, province) {
      // 检查是否已存在相同的搜索记录
      const existingIndex = this.searchHistory.findIndex(
        item => item.city === city && item.province === province
      )
      
      // 如果存在，先移除旧记录
      if (existingIndex !== -1) {
        this.searchHistory.splice(existingIndex, 1)
      }
      
      // 添加到搜索历史最前面
      this.searchHistory.unshift({
        city,
        province,
        timestamp: new Date().toISOString()
      })
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }
      
      // 保存到本地存储
      localStorage.setItem('weatherSearchHistory', JSON.stringify(this.searchHistory))
    },
    
    // 加载搜索历史
    loadSearchHistory() {
      try {
        const history = localStorage.getItem('weatherSearchHistory')
        if (history) {
          this.searchHistory = JSON.parse(history)
        }
      } catch (error) {
        console.error('加载搜索历史失败:', error)
        this.searchHistory = []
      }
    },
    
    // 清除搜索历史
    clearSearchHistory() {
      this.searchHistory = []
      localStorage.removeItem('weatherSearchHistory')
    }
  }
}) 